package com.wsoft.hr.pm.query.process.template;

import cn.hutool.core.collection.CollUtil;
import com.wsoft.core.validate.ValidList;
import com.wsoft.hr.pm.enums.HrProcessFlowStageEnum;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import javax.validation.Valid;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 模版考核流程主表
 * </p>
 *
 * @author zhonglj
 * @since 2025年02月28日 18:12:47
 */
@Data
public class HrPmProcessTemplateQuery {
    @NotBlank(message = "流程阶段不能为空!")
    @Schema(description = "流程阶段")
    private String flowStage;

    @Schema(description = "工作流流程定义key")
    private String procDefKey;

    @Schema(description = "排序")
    private Integer sort;

    @Valid
    @NotNull(message = "卡片列表不能为空!")
    @Schema(description = "考核流程卡片列表")
    private ValidList<HrProcessTemplateCardQuery> cards;

    @AssertTrue(message = "卡片排列不符合规则")
    public boolean isCardLayoutValid() {
        if (CollUtil.isEmpty(cards)) return true;

        boolean isPerformanceStage = HrProcessFlowStageEnum.PERFORMANCE_SCORE.getType().equals(this.flowStage);

        // 按纵向节点分组（serialSort相同为一组）
        Map<Integer, List<HrProcessTemplateCardQuery>> verticalGroups = cards.stream()
                .collect(Collectors.groupingBy(HrProcessTemplateCardQuery::getSerialSort));

        // 验证纵向节点数量
        int verticalCount = verticalGroups.size();
        if ((!isPerformanceStage && verticalCount > 3) || (isPerformanceStage && verticalCount > 10)) {
            return false;
        }

        // 验证每个纵向节点内的横向数量
        return verticalGroups.values().stream().allMatch(group -> {
            // 统计横向节点数量
            long horizontalCount = group.size();
            return horizontalCount <= 5;
        });
    }
}
